﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Secondhand_Book_Trade
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // 如果有分类参数，自动筛选
                if (Request.QueryString["cat"] != null)
                {
                    string cat = Request.QueryString["cat"];
                    SqlDataSourceBooks.SelectCommand += " AND b.CategoryID = @CategoryID";
                    SqlDataSourceBooks.SelectParameters.Add("CategoryID", cat);
                }
            }
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string keyword = txtKeyword.Text.Trim();
            string category = ddlCategory.SelectedValue;

            string sql = @"SELECT b.BookID, b.Title, b.Author, b.Price, c.CategoryName, b.CoverUrl, b.Description
                           FROM Books b
                           LEFT JOIN Categories c ON b.CategoryID = c.CategoryID
                           WHERE b.Status=1";

            if (!string.IsNullOrEmpty(category))
            {
                sql += " AND b.CategoryID = @CategoryID";
                SqlDataSourceBooks.SelectParameters.Clear();
                SqlDataSourceBooks.SelectParameters.Add("CategoryID", category);
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                sql += " AND (b.Title LIKE @Keyword OR b.Author LIKE @Keyword OR b.Description LIKE @Keyword)";
                if (SqlDataSourceBooks.SelectParameters["Keyword"] == null)
                    SqlDataSourceBooks.SelectParameters.Add("Keyword", "%" + keyword + "%");
                else
                    SqlDataSourceBooks.SelectParameters["Keyword"].DefaultValue = "%" + keyword + "%";
            }
            SqlDataSourceBooks.SelectCommand = sql;
        }
    }
}